#include "libreadkeys.h"

char * key[K_MAX];
int MAX_LEN = 5;
struct termios ts;
	
int rk_readkey(enum keys * k) {
	key[K_UP] = "\033[A";
	key[K_DOWN] = "\033[B";
	key[K_LEFT] = "\033[D";
	key[K_RIGHT] = "\033[C";
	key[K_F5] = "\033[15~";
	key[K_ESC] = "\033\033";
	key[K_ENTER] = "\n";
	key[K_UNKNOWN] = "";

	int len = 1, i = 0, f = 1;
	char tmp[MAX_LEN + 1];
	
	*k = K_UNKNOWN;
	while (read(1, &tmp[len-1], 1) > 0 && len <= MAX_LEN + 1) {
		tmp[len] = 0;
		for (i = K_UNKNOWN; i < K_MAX; i++) {
			if (key[i][len - 1] != tmp[len - 1] && f == 0) {
				f = 0;
			} else {
				f = 1;
				if (strlen(key[i]) == len) {	
					if (strcmp(key[i], tmp) == 0) {
						*k = i;
						return 0;
					}
				}
			}
		}
		if (f == 0) {
			break;
		}
		len++;
		f = 0;
		tmp[len] = 0;
	}
	*k = K_UNKNOWN;
	return 0;
}

int rk_mytermsave(void) {	
	return (tcgetattr(1, &ts));
}

int rk_mytermrestore(void) {
	tcsetattr(1, TCSADRAIN, &ts);
	return 0;
}

int rk_mytermregime (int regime, int vtime, int vmin, int echo, int sigint) {
	struct termios tmp;
	if (tcgetattr(1, &tmp) == -1) { 
		return -1;
	} 
	if (regime == 1) {
		tmp.c_lflag = tmp.c_lflag | ICANON;
	} else if (regime == 0) {
		tmp.c_lflag = tmp.c_lflag & (~ICANON);
		if (echo == 1) {
			tmp.c_lflag = tmp.c_lflag | ECHO;
		} else if (echo == 0) {
			tmp.c_lflag = tmp.c_lflag & (~ECHO);
		}
		if (sigint == 1) { 
			tmp.c_lflag = tmp.c_lflag | ISIG;
		} else if (sigint == 0) {
			tmp.c_lflag = tmp.c_lflag & (~ISIG);
		}
		tmp.c_cc[VMIN] = vmin;
		tmp.c_cc[VTIME] = vtime;
	} else {
		return -1;
	}
	tcsetattr(1, TCSADRAIN, &tmp);
	return 0;
}
